const kingdeeOldApientity = require('../../libs-jdy/isvopenapi/kingdeeOldApi');
const kingdeeAuthToken = require('../../libs-jdy/openapi/kingdeeAuthToken');
const logAppRepository = require('../repository/log-app-repository');
const redisUtil = require('../libs/redis-util');

/**
 * 旧版本自定义接口调用
 */
const kingdeeOldApi = async (ctx) => {
    await Promise.resolve().then(async () => {
        try {
            const params = ctx.request.body;
            const {kingdeeurl} = ctx.request.headers;
            const {zlzouterinstanceid} = ctx.request.headers;
            let resData;
            let method = ctx.method;
            let pushAppAuthorizeList;
            let datas = {
                outerInstanceId: zlzouterinstanceid
            }
            const accountData = await logAppRepository.getAccountAppCount(datas);
            console.log(accountData.accountName);
            if(!accountData){
                ctx.body = Res.error(Mes.AUTH_ERROR);
                return
            }
            resData = await redisUtil.get(`jwt:${zlzouterinstanceid}:pushAppAuthorizeList`);
            if (!resData) {
                let kingdeeData = {
                    clientID: accountData.clientId,
                    clientSecret: accountData.clientSecret,
                    appKey: accountData.appKey,
                    outerInstanceId: accountData.outerInstanceId,
                }
                const auth = new kingdeeAuthToken(kingdeeData);
                const {pushAppAuthorizeList, appTokenList} = await auth.getAppToken();
                pushAppAuthorizeList.app_token = appTokenList['app-token'];
                pushAppAuthorizeList.access_token = appTokenList.access_token;
                pushAppAuthorizeList.clientSecret = kingdeeData.clientSecret;
                await redisUtil.set(`jwt:${data.outerInstanceId}:pushAppAuthorizeList`, JSON.stringify(pushAppAuthorizeList), 9000);
            } else {
                pushAppAuthorizeList = JSON.parse(resData);
            }
            const kingdeeOldApis = new kingdeeOldApientity(pushAppAuthorizeList);
            const kingdeeOldApiRes = await kingdeeOldApis.kingDeeOldIsv(params, params, kingdeeurl, method);
            if(kingdeeOldApiRes.errorCode==="500"){
                ctx.body = Res.error("接口返回失败", {
                    code: kingdeeOldApiRes.errorCode,
                    message: kingdeeOldApiRes.message
                });
                return
            }
            ctx.body = await Res.success(kingdeeOldApiRes);
        } catch (error) {
            ctx.body = Res.error("接口返回失败", {
                code: -100,
                message: error
            });
            return
        }
    })
}
module.exports = {
    kingdeeOldApi
};